<?php

namespace app\store\controller;

use app\admin\common\Base;
use think\Db;
use app\admin\common\Excel;

//调拨单
class Move extends Base
{
    public function index()
    {

        $data = $this->request->param();

        $this->assign('o_type', 6); //高级搜索状态（6：调拨单记录）

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            //搜索
            if (isset($data['search'])) {

                if ($data['search'] == 0) {

                    $field = 'sn';
                    $sonField = 'mark';
                    $keywork = $data['matchCon'];
                    $value = ['move_good', 'move_id'];
                    $where = getSearch($field, $sonField, $keywork, $value, $type = true);

                    $time1 = strtotime($data['datew']);
                    $time2 = strtotime("+1 day", strtotime($data['dateo']));

                    $sql = Db::name('move')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where($where);
                    $sql = !isset($time1) && !isset($time2) ? $sql : $sql->whereTime('addtime', 'between', [$time1, $time2]);
                    $list = $sql->order('id desc')->limit($start, $limit)->select();
                    $count = sizeof($list);

                    //高级搜索
                } else {

                    $time1 = strtotime($data['fromDate']);
                    $time2 = strtotime("+1 day", strtotime($data['toDate']));

                    $son = ['ck_out', 'ck_in', 'goods_id']; //子表字段循环查询
                    $sonkey = [$data['storeOutId'], $data['storeInId'], $data['goods_id']];

                    $tables = ['add_user', 'last_user', 'shenhe_user', 'status']; //主表字段查询
                    $keywork = [$data['usersCreatId'], $data['usersModifyId'], $data['usersChecksId'], $data['checkStatusId']];

                    //子表查询方法    
                    $sql = empty($stime[0]) && empty($stime[1]) && empty($data['storeOutId']) && empty($data['storeInId']) && empty($data['goods_id']) ? '' : Db::name('move_good')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId);
                    //子表模糊查询
                    $sql = empty($data['remarkCon']) ? $sql : $sql->where('mark', 'like', '%' . $data['remarkCon'] . '%');
                    $sql = empty($time1) ? $sql : $sql->whereTime('addtime', 'between', [$time1, $time2]);
                    //子表精确查询
                    for ($i = 0; $i < count($son); $i++) {
                        $sql = $sonkey[$i] == '' ? $sql : $sql->where($son[$i], $sonkey[$i]);
                    }
                    $sql = !empty($sql) ? $sql->column('move_id') : '';
                    $lists = Db::name('move')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId);
                    $lists = empty($sql) ? $lists : $lists->where('id', 'in', $sql);
                    //精确查询
                    for ($j = 0; $j < count($keywork); $j++) {
                        $lists = $keywork[$j] == '' ? $lists : $lists->where($tables[$j], $keywork[$j]);
                    }
                    $list = $lists->order('id desc')->limit($start, $limit)->select();
                    $count = sizeof($list);
                }
            } else {

                if ($map == '') {
                    $list = Db::name('move')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                    $count = Db::name('move')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                } else {
                    $list = Db::name('move')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                    $count = Db::name('move')->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                }
            }

            foreach ($list as $key => &$val) {
                $move_good = Db::name('move_good')->where('move_id', $val['id'])->select();
                $goods_name = []; //商品名称
                $goods_type = []; //商品类别
                $goods_mark = []; //商品备注
                $goods_num = []; //商品数量
                $goods_dw = []; //商品单位
                $goods_ck2 = []; //商品调出仓库
                $goods_ck1 = []; //商品调入仓库
                $goods_marks = []; //商品分录备注
                foreach ($move_good as $ke => $va) {
                    $g = Db::name('goods')->where('id', $va['goods_id'])->find();
                    $g_name = $g['name'];
                    $g_type = Db::name('goods_category')->where('id', $g['goods_category_id'])->value("name");
                    $g_mark = $g['mark'];
                    $g_num = $va['num'];
                    $g_dw = $va['dw'];
                    $g_ck2 = $va['ck_in'];
                    $g_ck1 = $va['ck_out'];
                    if (empty($va['mark'])) {
                        $va['mark'] = "暂无";
                    }
                    $g_marks = $va['mark'];

                    array_push($goods_name, $g_name);
                    array_push($goods_type, $g_type);
                    array_push($goods_mark, $g_mark);
                    array_push($goods_num, $g_num);
                    array_push($goods_dw, $g_dw);
                    array_push($goods_ck2, $g_ck2);
                    array_push($goods_ck1, $g_ck1);
                    array_push($goods_marks, $g_marks);
                }

                $val['goods_name'] = $goods_name;
                $val['goods_type'] = $goods_type;
                $val['goods_mark'] = $goods_mark;
                $val['goods_num'] = $goods_num;
                $val['goods_dw'] = $goods_dw;
                $val['goods_ck2'] = $goods_ck2;
                $val['goods_ck1'] = $goods_ck1;
                $val['goods_marks'] = $goods_marks;
                $val['col_h'] = count($goods_name); //行高
                $val['zt'] = $val['status']; //行高

                $val['time'] = date('Y-m-d', $val['time']);
            }
            //halt($list);
            return $this->grid_data($list, $count, $page, $limit);
        }
        $today = date('Y-m-d', time());
        $mon_start = date('Y-m', time()) . '-01';
        $this->assign('today', $today);
        $this->assign('mon_start', $mon_start);
        return $this->fetch();
    }


    public function edit()
    {
        $data = $this->request->param();
        $today = date('Y-m-d', time());
        $store = Db::name('store')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('sort desc,id asc')->select();




        $this->assign('store', $store);
        $this->assign('today', $today);
        return $this->fetch('edit');
    }


    public function add()
    {
        $today = date('Y-m-d', time());
        $store = Db::name('store')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('sort desc,id asc')->select();
        $this->assign('store', $store);
        $this->assign('today', $today);
        return $this->fetch();
    }


    // 添加调拨单-更新
    public function save()
    {
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();
        $post = $data;
        // 启动事务
        Db::startTrans();
        $movegood = $data['movedata'];
        unset($data['movedata']);


        $data['addtime'] = time();
        $data['enterprise_id'] = $this->EnterpriseId;
        $data['updatetime'] = time();
        $data['time'] = strtotime($data['time']);
        $data['add_user'] = $this->Userinfo['id'];
        $data['last_user'] = $this->Userinfo['id'];


        $insert_id = Db::name('move')->insertGetId($data);
        if ($insert_id) {
            //更新字表
            $arr = [];
            foreach ($movegood as $key => $val) {

                if ($val['goodsid'] != "0" && $val['ck1_id'] != "0" && $val['ck2_id'] != "0") {
                    $ins = [
                        'addtime' => time(),
                        'updatetime' => time(),
                        'move_id' => $insert_id,
                        'enterprise_id' => $this->EnterpriseId,
                        'goods_id' => $val['goodsid'],
                        'num' => $val['shuliang'],
                        'dw' => $val['dw'],
                        'ck_in' => $val['ck2_id'],
                        'ck_out' => $val['ck1_id'],
                        'mark' => $val['mark']
                    ];
                    array_push($arr, $ins);
                }
            }
            if (count($arr) > 0) {
                $res = Db::name('move_good')->insertAll($arr);
                if ($res) {
                    // 提交事务
                    Db::commit();
                    $status = 1;
                    $msg = "添加成功";
                }
            }
        }
        if ($status != 1) {
            // 回滚事务
            Db::rollback();
        }

        return ['status' => $status, 'msg' => $msg];
    }
    public function export()
    {
        $data = $this->request->param();
        $rowid = explode(" ", $data['rowid']);
        // halt($rowid);
        $title = [
            'addtime' => '单据日期',
            'sn' => '单据编号',
            'add_user' => '制单人',
            'mark' => '单据备注',
            'goods_sn' => '商品编号',
            'goods_name' => '商品名称',
            'goods_model' => '规格型号',
            'goods_attribute' => '属性',
            'goods_code' => '商品条码',
            'code_txm' => '属性条码',
            'dw' => '单位',
            'goods_category_id' => '商品类别',
            'goods_mark' => '商品备注',
            'num' => '数量',
            'ck_in' => '调出仓库',
            'ck_out' => '调入仓库',
            'move_mark' => '备注'
        ];
        $a = '';
        $arr_list = [];
        //查询子表
        $list = Db::name('move_good')->alias('a')->join('move b', 'a.move_id = b.id')->where('a.move_id', 'in', $rowid)->where('a.is_del', 0)->where('a.enterprise_id', $this->EnterpriseId)->order('b.id desc')->select();
        // halt($list);
        //子表遍历输出的内容
        foreach ($list as $k => &$v) {
            //查询商品表追加内容
            $goods = db('goods')->where('is_del', 0)->where($this->EnterpriseId)->where('id', $v['goods_id'])->find();
            $v['goods_sn'] = $goods['sn'];
            $v['goods_name'] = $goods['name'];
            $v['goods_model'] = $goods['model'];
            $v['goods_attribute'] = $goods['attribute'];
            $v['goods_code'] = $goods['code'];
            $v['code_txm'] = '';
            $v['goods_category_id'] = $goods['goods_category_id'];
            $v['goods_mark'] = $goods['mark'];
            $V['ck_in'] = db('store')->where('is_del', 0)->where($this->EnterpriseId)->where('id', $v['ck_in'])->value('name');
            $V['ck_out'] = db('store')->where('is_del', 0)->where($this->EnterpriseId)->where('id', $v['ck_out'])->value('name');
            $v['move_mark'] = db('move_good')->where('is_del', 0)->where($this->EnterpriseId)->where('move_id', $v['id'])->value('mark');
            array_push($arr_list, $v);
            //追加空格行 输出 合计
            $a = empty($a) ? $a = ['id' => '0']  : $a;
            if ($a['id'] !== $v['id']) {
                //计算总数
                $num = db('move_good')->where('is_del', 0)->where($this->EnterpriseId)->where('move_id', $v['id'])->sum('num');
                $hj = [
                    'id' => $v['id'] - 1,
                    'addtime' => '',
                    'sn' => $v['sn'],
                    'add_user' => '',
                    'mark' => '',
                    'goods_sn' => '合计',
                    'goods_name' => '',
                    'goods_model' => '',
                    'goods_attribute' => '',
                    'goods_code' => '',
                    'code_txm' => '',
                    'dw' => '',
                    'goods_category_id' => '',
                    'goods_mark' => '',
                    'num' => $num,
                    'ck_in' => '',
                    'ck_out' => '',
                    'move_mark' => ''
                ];
                array_push($arr_list, $hj);
            }

            $a = $v;
        }
        array_multisort(array_column($arr_list, 'id'), SORT_DESC, $arr_list); //按照ID大小排序
        // halt($arr_list);
        //添加标题到数组头部
        array_unshift($arr_list, $title);
        $kong_arr = $title;
        foreach ($kong_arr as $ke1 => $va1) {
            $kong_arr[$ke1] = '';
        }
        for ($i = 0; $i < 3; $i++) {
            array_unshift($arr_list, $kong_arr);
        }
        //根据此参数获取数据中的值，要与表格标题键名对应
        $keys = [];
        foreach ($title as $k2 => $v2) {
            array_push($keys, $k2);
        }
        $merge = [];
        $options = [];
        $o_type = -1;
        $merge = [ //合并
            'start' => 5,
            'arr_zimu' => ['A', 'B', 'C', 'D'],
            'keyword' => 'sn',
        ];
        $options = [
            'alignCenter' => ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q'], //居中
            'bold' => ['A1:N3', 'A4:N4'], //加粗
            'fontSize' => ['zimu' => ['A1'], 'size' => 20], //字体大小
        ];
        $title = [ //标题
            'title' => "调拨单记录",
            'max_zimu' => "Q",
            'number' => '3',
        ];
        $excel_export_title = "调拨单记录_" . date('Y-m-d_His') . '.xlsx'; //文件名称
        $excel = new Excel();
        $excel->exportExcel($arr_list, $keys, $excel_export_title, $options, $o_type, $merge, $title);

        exit();
    }
}
